import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//组合总和
//测试链接：https://leetcode.cn/problems/combination-sum/
public class CombinationSum {
    List<List<Integer>> ans;
    List<Integer> path;
    int sum = 0;
    int target;

    public List<List<Integer>> combinationSum(int[] candidates, int _target) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        target = _target;
        Arrays.sort(candidates);

        dfs(candidates,0);
        return ans;
    }

    public void dfs(int[] nums, int pos) {
        if(sum == target) {
            ans.add(new ArrayList<>(path));
            return;
        }

        for(int i = pos; i < nums.length; i++) {
            if(nums[i] + sum > target) return;

            sum += nums[i];
            path.add(nums[i]);
            dfs(nums,i);
            path.remove(path.size()-1);
            sum -= nums[i];
        }
    }
}
